<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            background-color:rgb(244, 249, 249);
        }
        #box1{
            height: 150px;
            width: 150px;
            /* left: 100px; */
            /* right: 100px; */
            /* top: 20px; */
            background-color: aqua;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="box1">
        <img src="../img/renwu.png" alt="">
    </div>
    <script>
        //获取div
        let box = document.getElementById('box1');
        let speed = 0;
        let keywords = 0;
        //设置一个定时器
        setInterval(() => {
            
            if(keywords == 37){
                //左
                box.style.left = box.offsetLeft -speed +'px';
            }else if(keywords ==38){
                // 上
                box.style.top = box.offsetTop -speed +'px';
            }else if(keywords == 39){
                //右
                box.style.left = box.offsetLeft + speed +'px';
            }else if(keywords == 40){
                // 下
                box.style.top = box.offsetTop  + speed +'px';
            }
        }, 30);

        //为文档绑定键盘响应事件
        document.addEventListener('keydown',(event)=>{
            if(event.ctrlKey){
                speed = 50;
            }else{
                speed = 20;
            }

            //获取上下左右的值
            keywords = event.keyCode;

            //当按键松开，keywords == 0；
            document.onkeyup = function(){
                keywords = 0;
            }

        })
    </script>
</body>
</html>